package com.furongji.education.schedule;

import com.furongji.common.utils.RedissonLockUtil;
import com.furongji.education.domain.vo.DailyStatisticsVo;
import com.furongji.education.service.DailyStatisticsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
@Slf4j
public class DailyDashboardDataScheduler {

    private final DailyStatisticsService dailyStatisticsService;

    private final RedissonLockUtil redissonLockUtil;

    private final RedisTemplate<String, Object> redisTemplate;

    private static final String LOCK_KEY = "lock:dashboard:summary";

    @Scheduled(cron = "0 0 * * * ?")
    public void refreshDashboardCache() {
        boolean locked = redissonLockUtil.tryLock(LOCK_KEY, 0, 10, TimeUnit.SECONDS);
        if (!locked) {
            log.warn("未获取到刷新缓存锁");
            return;
        }
        try {
            String date = LocalDate.now().toString();
            log.info("开始刷新首页统计缓存，时间：{}", LocalDate.now());
            DailyStatisticsVo statistics = dailyStatisticsService.getSummaryStatistics(date);
            String cacheKey = "statistics:summary:" + date;
            redisTemplate.opsForValue().set(cacheKey, statistics, 65, TimeUnit.MINUTES);
        } catch (Exception e) {
            log.error("刷新首页统计缓存失败", e);
        } finally {
            redissonLockUtil.unlock(LOCK_KEY);
            log.info("释放刷新首页统计缓存的锁");
        }
    }
}
